<script>
import {getToken, saveToken} from "@/store/token";
import axios from "axios";

export default {
  name: "myInfo",
  data() {
    var checkEmail = (rule, value, callback) => {
      const regUser = /^([a-zA-Z0-9]+[-_]?)+@[a-zA-Z0-9]+\.[a-z]+$/
      if (regUser.test(value)) {
        return callback();
      }
      //console.log(value)
      if (value === undefined || value.length === 0) {
        callback(new Error('邮箱不能为空'));
      } else {
        callback(new Error('邮箱验证不合法'));
      }
    }
    return {
      activeName: 'first',
      codeShow: true,
      count: '',
      timer: null,
      user: {
        user: "",
        nickName: "",
        userEmail: ""
      },
      ruleForm: {
        updateNickName: ''
      },
      emailForm: {
        newEmail: "",
        userEmail: ""
      },
      rules: {
        updateNickName: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
        ],
        newEmail: [{validator: checkEmail, trigger: 'blur'}],
        userEmail: [{validator: checkEmail, trigger: 'blur'}],
      }
    }
  },
  methods: {
    //handleClick(tab, event) {
    //  console.log(tab, event);
    //},
    submitForm(ruleForm) {
      this.$api.user.updateUser({
        id: this.user.id,
        nickName: this.ruleForm.updateNickName
      }).then((res) => {
        this.$message({
          message: '修改成功',
          type: 'success'
        });
        this.getUserByPhone(this.user.phone)
        this.$refs[ruleForm].resetFields();
      }).catch((res) => {
        this.$message.error('请求失败' + res);
      })
    },
    getUserByPhone(phone) {
      this.$api.user.getUserByPhone(phone).then((res) => {
        this.user = res.data.content;
      }).catch((res) => {
        this.$message.error('请求失败' + res);
      })
    },
    hidePhone(phone) {
      if (typeof (phone) == "string")
        return phone.slice(0, 3) + '****' + phone.slice(7);
    },
    getEmailCode(formName) {  //获取验证码
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var Reg = /^([a-zA-Z0-9]+[-_]?)+@[a-zA-Z0-9]+\.[a-z]+$/
          // 正则验证
          if (Reg.test(this.user.userEmail)) {

            this.$api.user.emailCode(
                this.user.user,
                this.emailForm.userEmail,
                ""
            ).then(res => {
              if (res.data.success) {
                this.$message.info('验证码邮件已经发送');
              } else {
                this.$message.error(res.data.message);
              }
              const TIME_COUNT = 60;
              if (!this.timer) {
                this.count = TIME_COUNT;
                this.codeShow = false;
                this.timer = setInterval(() => {
                  if (this.count > 0 && this.count <= TIME_COUNT) {
                    this.count--;
                  } else {
                    this.codeShow = true;
                    clearInterval(this.timer);
                    this.timer = null;
                  }
                }, 1000)
              }
            })
          } else {
            this.$message.info('邮箱格式不正确');
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    submitEmail(formName) {  //确定更换
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var Reg = /^([a-zA-Z0-9]+[-_]?)+@[a-zA-Z0-9]+\.[a-z]+$/
          // 正则验证与验证码
          if (Reg.test(this.user.userEmail) && this.emailForm.code) {
            this.$api.user.updateEmail(
                this.user.user,
                this.emailForm.userEmail,
                this.emailForm.code,
                ""
            ).then(res => {
              if (res.data.success) {
                this.$message.info('更换成功');
                this.$api.user.getUserByPhone(this.user.phone).then(res => {
                  this.user = res.data.content
                  saveToken("user", JSON.stringify(res.data.content))
                })
                this.$refs[formName].resetFields();
              } else {
                this.$message.error(res.data.message ? "服务器原因，更换失败" : res.data.message);
              }
            })
          } else {
            this.$message.error('验证码未输入');
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  },
  mounted() {
    //let token = getToken("Authorization");
    this.user = JSON.parse(getToken("user"));
    //this.getUserByPhone(token)
  }
}
</script>
<template>
  <div>
    <span style="font-size: 18px;">个人资料</span>
    <el-tabs v-model="activeName">
      <el-tab-pane label="个人信息" name="first">
        <div class="my-info-header">
          <div>
            <img style="border-radius: 40px" src="../../assets/user.jpg" alt="">
          </div>
          <div style="margin-left: 10px">
            <div style="display: flex;margin: 5px">
              <label class="name">用户名：</label><span>{{ hidePhone(user.phone) }}</span>
            </div>
            <div style="display: flex;margin: 5px">
              <label class="name">昵&nbsp;&nbsp;&nbsp;称：</label><span>{{ user.nickName }}</span>
            </div>
            <div style="display: flex;margin: 5px">
              <label class="name">邮&nbsp;&nbsp;&nbsp;箱：</label>
              <span style="color:#8f8f8f;">{{ user.userEmail.slice(0, 3) + '****' + user.userEmail.slice(7) }}</span>
            </div>

          </div>
        </div>
        <div style="margin: 20px">
          <div>
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="60px" class="demo-ruleForm">
              <el-form-item label="昵称" prop="updateNickName">
                <el-input style="width: 200px;" v-model="ruleForm.updateNickName" placeholder="请输入昵称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="更换邮箱" name="email">
        <div style="margin: 20px">
          <div>
            <el-form :model="emailForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
              <el-form-item>
                <span style="color:#8f8f8f;">原始邮箱：{{ user.userEmail }}</span>
              </el-form-item>
              <el-form-item label="请输入新邮箱" prop="userEmail">
                <el-input style="width: 200px;" v-model="emailForm.userEmail" placeholder="请输入邮箱"></el-input>
              </el-form-item>
              <el-form-item label="验证码">
                <el-input style="width: 200px;" v-model="emailForm.code" placeholder="邮箱验证码"></el-input>
                <span v-if="codeShow" style="color:red;margin-left: 10px;cursor: pointer;"
                      @click="getEmailCode('ruleForm')">获取验证码</span>
                <!-- 倒计时 -->
                <span v-if="!codeShow" style="margin-left: 10px;" class="count">{{ count }}秒后重试</span>
              </el-form-item>
              <!--<el-form-item label="请输入新邮箱" prop="newEmail">-->
              <!--  <el-input style="width: 200px;" v-model="emailForm.newEmail" placeholder="请输入新邮箱"></el-input>-->
              <!--</el-form-item>-->
              <el-form-item>
                <el-button type="primary" @click="submitEmail('ruleForm')">确定更换</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-tab-pane>
      <!--<el-tab-pane label="头像照片" name="second">这里显示头像</el-tab-pane>-->
    </el-tabs>
  </div>
</template>

<style scoped>
.my-info-header {
  padding-left: 20px;
  height: 120px;
  display: flex;
  align-items: center;
  background: #f2f2f2;
  width: 100%;
}

.name {
  width: 66px;
  display: flex;
  justify-content: space-evenly;
  color: #8a8d8e;
}
</style>